package cn.com.darly.vpm.mobile.cfg;

import cn.com.darly.vpm.framework.common.DateUtil;
import cn.com.darly.vpm.framework.common.StringDiyUtils;
import cn.com.darly.vpm.framework.common.UuidGenerateUtil;
import cn.com.darly.vpm.framework.common.useragent.UserAgent;
import cn.com.darly.vpm.framework.systemlog.Logger;
import cn.com.darly.vpm.mobile.api.BaseMobileApi;
import cn.com.darly.vpm.mobile.session.SessionUtil;
import cn.com.darly.vpm.security.system.bean.SystemLog;
import cn.com.darly.vpm.security.user.bean.User;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Author : ZhangYuHui
 * Date : 2017/11/14
 * TODO :
 */
public class MobileBaseController {

    @Autowired
    BaseMobileApi logApi;

    @Resource
    MqttPahoMessageHandler mqtt;


    public Logger logger = new Logger(getClass());
    //--------------------------实现前端接口返回格式-----------------------------------------
    Map<String, Object> resultMap;

    /**
     * 初始化返回结果集
     */
    protected void initResultMap() {
        resultMap = new HashMap<>();
    }
    /**
     * 请求的页码
     */
    public int pageNo = 1;
    /**
     * 每页返回数据量
     */
    public int pageSize = 10;
    /**
     *  正确接口数据返回
     */
    protected void dataResult(String code, String desc, Object data, HttpServletRequest request, HttpServletResponse response) {
        this.initResultMap();
        resultMap.put(ResponseUtil.RES_KEY_CODE, code);
        resultMap.put(ResponseUtil.RES_KEY_DESC, desc);
        resultMap.put(ResponseUtil.RES_KEY_RESULT, data);
        resultMap.put(ResponseUtil.RES_KEY_TIME, DateUtil.now());
        ResponseUtil.printWriteResponse(request.getParameter("callback"), resultMap, response);
    }

    /**
     * 简单格式返回
     */
    protected void simpleResult(String code, String desc, HttpServletRequest request, HttpServletResponse response) {
        this.initResultMap();
        resultMap.put(ResponseUtil.RES_KEY_CODE, code);
        resultMap.put(ResponseUtil.RES_KEY_DESC, desc);
        resultMap.put(ResponseUtil.RES_KEY_TIME, DateUtil.now());
        ResponseUtil.printWriteResponse(request.getParameter("callback"), resultMap, response);
    }


    /**
     * 简单格式返回
     */
    protected void simplePageInfo(String code, String desc, PageInfo infos, HttpServletRequest request, HttpServletResponse response) {
        this.initResultMap();
        resultMap.put(ResponseUtil.RES_KEY_CODE, code);
        resultMap.put(ResponseUtil.RES_KEY_DESC, desc);
        resultMap.put(ResponseUtil.RES_KEY_PAGESIZE, infos.getPageSize());
        resultMap.put(ResponseUtil.RES_KEY_PAGE, infos.getPageNum());
        resultMap.put(ResponseUtil.RES_KEY_TOTALSIZE, infos.getTotal());
        resultMap.put(ResponseUtil.RES_KEY_TOTALPAGE, infos.getPages());
        resultMap.put(ResponseUtil.RES_KEY_RESULT, infos.getList());
        resultMap.put(ResponseUtil.RES_KEY_TIME, DateUtil.now());
        ResponseUtil.printWriteResponse(request.getParameter("callback"), resultMap, response);
    }


    /**
     * 获取当前登录人信息
     * @param token
     * @return
     */
    public User getLoginData(String token) {
        Object user = SessionUtil.SESSION_MAP.get(token);
        return (User)user;
    }

    /** 获取请求用户使用的设备信息
     * @param request
     * @return
     */
    public String findBrowser(HttpServletRequest request){
        String version = request.getHeader("version");
        if (!StringDiyUtils.isEmpty(version)&&version.contains("Android")){
            return "Android";
        }else if (!StringDiyUtils.isEmpty(version)&&version.contains("IOS")){
            return "IOS";
        }else {
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            return userAgent.getBrowser().getName()+userAgent.getOperatingSystem().getName();
        }
    }


    /**
     * 保存日誌的消息類
     * @param userid 登錄用戶的id
     * @param status 日志状态（0正常状态，1异常状态）
     * @param type 日志类型（0用户操作记录，1系统信息，2设备信息）
     * @param level 日志级别（0最高级，1次高级，2普通，3低级）
     * @param username 用户名
     * @param browser 浏览器
     * @param msg 信息
     */
    public void saveLog(String userid,String status,long type,long level,String username,String browser,String msg){
        SystemLog log = new SystemLog();
        log.setId(UuidGenerateUtil.getUUIDLong());
        logger.infoLine();
        log.setContent(browser+username+msg);
        log.setOperatorId(userid);
        log.setOperatorName(username);
        log.setOperationTime(DateUtil.now());
        log.setType(type);
        log.setLogLevel(level);
        log.setCreateDate(DateUtil.now());
        log.setCreateBy(username);
        log.setUpdateBy(username);
        log.setUpdateDate(DateUtil.now());
        log.setStatus(status);
        log.setBrowser(browser);
        logApi.saveLog(log);
        logger.info("["+username+msg+"]");
        logger.infoLine();
    }

    /**
     * 消息推送
     * @param msg
     * @param diveice
     */
    public void publishMessage(String msg,String diveice){
        //调用Mqtt发送好友申請信息(是否可以推送一个JSON字符串过去)
        Message<String> message = MessageBuilder.withPayload(msg).setHeader(MqttHeaders.TOPIC, "vpm@"+diveice).build();
        mqtt.handleMessage(message);
    }
}
